package gui;

import comm.OutputTask;
import structures.City;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: dna
 * Date: 28.04.13
 * Time: 17:21
 */
public class RemoveCityPopUp extends JFrame{

    private JLabel output;
    private JPanel labelContainer;
    private OutputTask outputTask;
    private Map<String, City> cities;
    private JComboBox<String> comboBox;

    public RemoveCityPopUp(Map<String, City> cities, JPanel labelContainer, JLabel output, OutputTask outputTask) {
        this.output = output;
        this.outputTask = outputTask;
        this.cities = cities;
        this.labelContainer = labelContainer;

        setTitle("Remove old City");
        setSize(new Dimension(200,50));
        setResizable(false);

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBorder(new EmptyBorder(5, 5, 5, 5));


        comboBox = new JComboBox<String>();
        for (String str : cities.keySet()){
            comboBox.addItem(str);
        }

        panel.add(comboBox);
        comboBox.addActionListener(new RemoveCity());

        getContentPane().setLayout(new FlowLayout());
        getContentPane().add(panel);

        pack();
    }

    private class RemoveCity implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            String value = (String)comboBox.getSelectedItem();
            try {
                outputTask.removeCity(cities.get(value));
                labelContainer.remove(cities.get(value).getPanel());
                cities.remove(value);
                output.setText("City " + value + " removed");
            } catch (ParserConfigurationException e1) {
                output.setText("<html><span style=\"color:red\">Error removing city " + value + "</span></html>");
            } catch (IOException e1) {
                output.setText("<html><span style=\"color:red\">Error removing city " + value + "</span></html>");
            } catch (TransformerException e1) {
                output.setText("<html><span style=\"color:red\">Error removing city " + value + "</span></html>");
            }
            dispose();
        }
    }
}
